package cn.iune.erp.payment;

import java.math.BigDecimal;
import java.sql.Date;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;


@Transactional
@Service
public class AccountPaymentDetailServiceImpl implements IAccountPaymentDetailService {
	
	
	@Autowired
	private IAccountPaymentDetailDao dao;
	

	@Transactional
	@Override
	public void insert(AccountPaymentDetail a) {
		// TODO Auto-generated method stub
		dao.insert(a);
	}

	@Transactional
	@Override
	public void delete(String fID) {
		// TODO Auto-generated method stub
		dao.delete(fID);
	}
	
	@Transactional
	@Override
	public void update(AccountPaymentDetail a) {
		// TODO Auto-generated method stub
		dao.update(a);
	}

	@Override
	public AccountPaymentDetail getByID(String fID) {
		return dao.getByID(fID);
	}

	@Transactional

	@Override
	public JSONObject save(JSONObject object) throws ParseException  {
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			AccountPaymentDetail obj = JSON.toJavaObject(javaObject, AccountPaymentDetail.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				AccountPaymentDetail objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}

	
	@Override
	public List<AccountPaymentDetail> getByWriteOffNo(String writeOffNo, String enterpriseNo) {
		return dao.getByWriteOffNo(writeOffNo, enterpriseNo);
	}
	
	
	
	@Override
	public List<AccountPaymentDetail> getByMasterID(String fMasterID) {
		return dao.getByMasterID(fMasterID);
	}

	@Transactional
	@Override
	public int deleteByMasterID(String fMasterID){
		List<AccountPaymentDetail> as = dao.getByMasterID(fMasterID);
		for(AccountPaymentDetail a:as){
			dao.delete(a.getfID());
		}
		return 0;
	}
	
	@Transactional
	@Override
	public int confirm(AccountPaymentDetail a) {
		a.setState("confirm");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int active(AccountPaymentDetail a) {
		a.setState("active");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int confirm(String fID) {
		AccountPaymentDetail a = dao.getByID(fID);
		return this.confirm(a);
	}
	
	@Transactional
	@Override
	public int active(String fID) {
		AccountPaymentDetail a = dao.getByID(fID);
		return this.active(a);
	}

	@Transactional
	@Override
	public int confirmByMasterID(String fMasterID){
		List<AccountPaymentDetail> as = dao.getByMasterID(fMasterID);
		for(AccountPaymentDetail a:as){
			this.confirm(a);
		}
		return 0;
	}
	
	@Transactional
	@Override
	public int activeByMasterID(String fMasterID){
		List<AccountPaymentDetail> as = dao.getByMasterID(fMasterID);
		for(AccountPaymentDetail a:as){
			this.active(a);
		}
		return 0;
	}
	
	@Transactional
	@Override
	public int open(String fID) {
		AccountPaymentDetail a = dao.getByID(fID);
		return this.open(a);
	}
	
	@Transactional
	@Override
	public int close(String fID) {
		AccountPaymentDetail a = dao.getByID(fID);
		return this.close(a);
	}
	
	@Transactional
	@Override
	public int open(AccountPaymentDetail a) {
		a.setStatus("open");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int close(AccountPaymentDetail a) {
		a.setStatus("close");
		dao.update(a);
		return 0;
	}

	@Transactional
	@Override
	public int openByMasterID(String fMasterID){
		List<AccountPaymentDetail> as = dao.getByMasterID(fMasterID);
		for(AccountPaymentDetail a:as){
			this.open(a);
		}
		return 0;
	}
	@Transactional
	@Override
	public int closeByMasterID(String fMasterID){
		List<AccountPaymentDetail> as = dao.getByMasterID(fMasterID);
		for(AccountPaymentDetail a:as){
			this.close(a);
		}
		return 0;
	}

	@Transactional
	@Override
	public int agreeIt(String fID, String tUsercode, String tUsername, String userId) {
		AccountPaymentDetail a = dao.getByID(fID);
		// TODO Auto-generated method stub
		
		return this.agreeIt(a, tUsercode, tUsername, userId);
	}

	@Transactional
	@Override
	public int unAgree(String fID) {
		AccountPaymentDetail a = dao.getByID(fID);
		// TODO Auto-generated method stub
		
		return this.unAgree(a);
	}
	
	//审核通过，改变审核状态为confirm
	@Transactional
	@Override
	public int agreeIt(AccountPaymentDetail a, String tUsercode, String tUsername, String userId) {
		
		a.setAudit("confirm");
		a.setConfirmDate(Utils.getCurrentDate());
		
		a.settUsercode(tUsercode);
		a.settUsername(tUsername);
		a.settDatetime(Utils.getCurrentDateTime());
		dao.update(a);
		
		return 0;
	}
	//审核拒绝，改变审核状态为active
	@Transactional
	@Override
	public int unAgree(AccountPaymentDetail a) {
		//判断是否可以撤销
		
		a.setAudit("active");
		a.setConfirmDate(null);
		
		a.settUsercode(null);
		a.settUsername(null);
		a.settDatetime(null);
		dao.update(a);

		return 0;
	}	

	@Transactional
	@Override
	public int agreeItByMasterID(String fMasterID, String tUsercode, String tUsername, String userId){
		List<AccountPaymentDetail> as = dao.getByMasterID(fMasterID);
		for(AccountPaymentDetail a : as){
			this.agreeIt(a, tUsercode, tUsername, userId);
		}
		return 0;
	}
	
	@Transactional
	@Override
	public int unAgreeByMasterID(String fMasterID){
		List<AccountPaymentDetail> as = dao.getByMasterID(fMasterID);
		for(AccountPaymentDetail a : as){
			this.unAgree(a);
		}
		return 0;
	}
	


	//打包子表
	@Override
	public AccountPaymentDetail packing(AccountPayment accountPayment, String clearType, String clearTypeLabel){
		
		AccountPaymentDetail obj = new AccountPaymentDetail();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		
		obj.setClearType(clearType);
		obj.setClearTypeLabel(clearTypeLabel);
		
		//单号
		
		obj.setSystemCode(accountPayment.getSystemCode());
		obj.setRevOpay(accountPayment.getRevOpay());
		obj.setDirection(accountPayment.getDirection());
		
		obj.setState(accountPayment.getState());
		obj.setStatus(accountPayment.getStatus());
		obj.setAudit(accountPayment.getAudit());
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setfMasterID(accountPayment.getfID());
		//单号/核销号
//		obj.setWriteOffNo(accountPayment.getAccountPaymentNo());
		//子表明细号
//		int maxDetailNo = accountPayment.getMaxDetailNo() + 1;
//		String accountInvoiceDetailNo = accountInvoice.getAccountInvoiceNo() + String.format("%05d", maxDetailNo);
//		obj.setAccountInvoiceNo(accountInvoiceDetailNo);
			
		obj.setDealObject(accountPayment.getDealObject());
		obj.setDealObjectLabel(accountPayment.getDealObjectLabel());
		obj.setCustomerID(accountPayment.getCustomerID());
		obj.setCustomerNo(accountPayment.getCustomerNo());
		obj.setShortName(accountPayment.getShortName());
		obj.setCustomerName(accountPayment.getCustomerName());
		
		obj.setOrderAmount(BigDecimal.ZERO);
		
//		obj.setPendingAmount(BigDecimal.ZERO);
		obj.setOrderAmountCleared(BigDecimal.ZERO);
		obj.setDiscountCash(BigDecimal.ZERO);
		
//		obj.setAccountPending(BigDecimal.ZERO);
		
		obj.setAccountClearPayable(BigDecimal.ZERO);
		obj.setAccountClearActual(BigDecimal.ZERO);
		obj.setAccountDiscountCash(BigDecimal.ZERO);

//		obj.setReceiveCashAmount(BigDecimal.ZERO);
//		obj.setGiveChangeAmount(BigDecimal.ZERO);
		
		obj.setEmployeeNo(accountPayment.getEmployeeNo());
		obj.setEmployeeName(accountPayment.getEmployeeName());
		
		obj.setComments("来自商城");
		
		obj.setcUsercode(accountPayment.getcUsercode());
		obj.setcUsername(accountPayment.getcUsername());
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(accountPayment.getUserId());
		obj.setEnterpriseNo(accountPayment.getEnterpriseNo());
		obj.setEnterpriseName(accountPayment.getEnterpriseName());
//		
		obj.setVersion(0);
		
		return obj;
	}
	
	//打包核销明细表（作为收付款明细表使用，不能作为主表使用）
	@Override
	public AccountPaymentDetail packing(
			String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String employeeNo 
			,String employeeName 
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		//SysInfo中记录的ID
//		final String APPID = "698decc4a8c6b4dae859d1aa4dc8d146";
		String APPID = null;
		
		
		AccountPaymentDetail obj = new AccountPaymentDetail();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		obj.setSystemCode(APPID);
		//单号
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setOrderAmount(BigDecimal.ZERO);
		
		obj.setPendingAmount(BigDecimal.ZERO);
		obj.setOrderAmountCleared(BigDecimal.ZERO);
		obj.setDiscountCash(BigDecimal.ZERO);
		
		obj.setOrderAmountTotal(BigDecimal.ZERO);
		
		obj.setAccountClearPayable(BigDecimal.ZERO);
		obj.setAccountClearActual(BigDecimal.ZERO);
		obj.setAccountDiscountCash(BigDecimal.ZERO);

//		obj.setReceiveCashAmount(BigDecimal.ZERO);
//		obj.setGiveChangeAmount(BigDecimal.ZERO);
		
		obj.setEmployeeNo(employeeNo);
		obj.setEmployeeName(employeeName);
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
//		
		obj.setVersion(0);
		
		return obj;
	}

	@Transactional
	@Override
	public AccountPaymentDetail accountPaymentDetailInsert(
			String writeOffNo,
			String fMasterID,
			String settleCategory,
			String settleCategoryLabel,
			
			int cashSettle,
			
			String clearType,
			String clearTypeLabel,
			
			String revOpay,
			int direction,
			
			String origin,
			String originName,
			String originNo,
			
			Date invoiceDate,
			String invoiceCode,
			
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,
			
			BigDecimal orderAmount,
			BigDecimal pendingAmount,
			BigDecimal orderAmountCleared,
			BigDecimal discountCash,
			
			String captionID,
			String captionNo,
			String captionName,
			String captionFullName,
			
			String orderNo,
			String projectNo,
			
			String cUsercode,String cUsername,String userId,
			String employeeNo,String employeeName,
			
			String enterpriseNo,
			String enterpriseName
			){
		
		String moneyType = null;
		String moneyTypeLabel = null;
		if("XSFP".equals(origin)) {
			moneyType = "1";
			moneyTypeLabel = "1.销售发票";
		}
		if("QTYS".equals(origin)) {
			moneyType = "2";
			moneyTypeLabel = "2.其他应收";
		}
//		if("SKDJ".equals(origin)) {
//			moneyType = "3";
//			moneyTypeLabel = "3.收款单";
//		}
		if("YSKD".equals(origin)) {
			moneyType = "4";
			moneyTypeLabel = "4.冲销预收款";
		}
//		if("RDJQ".equals(origin)) {
//			moneyType = "5";
//			moneyTypeLabel = "5.冲减代金券";
//		}
		
		if("CGFP".equals(origin)) {
			moneyType = "1";
			moneyTypeLabel = "1.采购发票";
		}
		if("QTYF".equals(origin)) {
			moneyType = "2";
			moneyTypeLabel = "2.其他应付";
		}
//		if("FKDJ".equals(origin)) {
//			moneyType = "3";
//			moneyTypeLabel = "3.付款单";
//		}
		if("YFKD".equals(origin)) {
			moneyType = "4";
			moneyTypeLabel = "4.冲销预付款";
		}
		if("FDJQ".equals(origin)) {
			moneyType = "5";
			moneyTypeLabel = "5.冲减代金券";
		}
		
		//打包主表AccountPayment
		AccountPaymentDetail accountPaymentDetail = this.packing(cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		accountPaymentDetail.setCashSettle(cashSettle);
		
		accountPaymentDetail.setClearType(clearType);
		accountPaymentDetail.setClearTypeLabel(clearTypeLabel);
		accountPaymentDetail.setBillType(moneyType);//款项类别
		accountPaymentDetail.setBillTypeName(moneyTypeLabel);//款项类别
		
		accountPaymentDetail.setState("confirm");
		accountPaymentDetail.setAudit("active");
		accountPaymentDetail.setOrderDate(Utils.getCurrentDate());
		accountPaymentDetail.setConfirmDate(Utils.getCurrentDate());
	
		accountPaymentDetail.setAccountPaymentNo(writeOffNo);
		accountPaymentDetail.setfMasterID(fMasterID);
		
		accountPaymentDetail.setDirection(direction);
		accountPaymentDetail.setRevOpay(revOpay);
		
		accountPaymentDetail.setEmployeeNo(employeeNo);
		accountPaymentDetail.setEmployeeName(employeeName);
		
		accountPaymentDetail.setOrigin(origin);
		accountPaymentDetail.setOriginName(originName);
		accountPaymentDetail.setOriginNo(originNo);
		
		accountPaymentDetail.setDealObject(dealObject);
		accountPaymentDetail.setDealObjectLabel(dealObjectLabel);
		accountPaymentDetail.setCustomerID(customerID);
		accountPaymentDetail.setCustomerNo(customerNo);
		accountPaymentDetail.setShortName(shortName);
		accountPaymentDetail.setCustomerName(customerName);
		
		//付款日期
	//	if(orderDate!=null && !orderDate.equals("")){
	//		accountPaymentDetail.setOrderDate(Date.valueOf(orderDate));
	//	}
		accountPaymentDetail.setSettleCategory(settleCategory);
		accountPaymentDetail.setSettleCategoryLabel(settleCategoryLabel);
		
//		accountPaymentDetail.setSettleDate(invoiceDate);
		accountPaymentDetail.setSettleCode(invoiceCode);
		
		//获取会计科目（结算账户）的全路径信息
	//	AccountCaption accountCaption = accountCaptionService.getByID(captionID);
	//	String captionFullNo = null;// accountCaption.getCaptionFullNo();
	//	String captionFullName = null;// accountCaption.getCaptionFullName();
		
		accountPaymentDetail.setCaptionID(captionID);
		accountPaymentDetail.setCaptionNo(captionNo);
		accountPaymentDetail.setCaptionName(captionName);
		accountPaymentDetail.setCaptionFullName(captionFullName);
		
		accountPaymentDetail.setOrderNo(orderNo);
		accountPaymentDetail.setProjectNo(projectNo);
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		accountPaymentDetail.setOrderAmount(orderAmount);//应收票据金额
		accountPaymentDetail.setPendingAmount(pendingAmount);//应收票据余额
		accountPaymentDetail.setOrderAmountCleared(orderAmountCleared);//核销金额
		accountPaymentDetail.setDiscountCash(discountCash);//折扣金额

		//账
		BigDecimal accountAmountCleared = orderAmountCleared.multiply(new BigDecimal(direction)).setScale(2);
		
//		if("SKDJ".equals(accountPaymentDetail.getOrigin()) || "FKDJ".equals(accountPaymentDetail.getOrigin())) {
//			//实收核销
//			accountPaymentDetail.setAccountClearActual(accountAmountCleared);
//			accountPaymentDetail.setAccountDiscountCash(BigDecimal.ZERO);
//		}
		
		if("YSKD".equals(accountPaymentDetail.getOrigin()) || "YFKD".equals(accountPaymentDetail.getOrigin()) || "SDJQ".equals(accountPaymentDetail.getOrigin()) || "FDJQ".equals(accountPaymentDetail.getOrigin())) {
			//实收核销
			accountPaymentDetail.setAccountClearPayable(accountAmountCleared);
			accountPaymentDetail.setAccountDiscountCash(BigDecimal.ZERO);
		}
		
		if("XSFP".equals(accountPaymentDetail.getOrigin()) || "QTYS".equals(accountPaymentDetail.getOrigin()) || "CGFP".equals(accountPaymentDetail.getOrigin()) || "QTYF".equals(accountPaymentDetail.getOrigin())) {
			//应收核销
			accountPaymentDetail.setAccountClearPayable(accountAmountCleared);
			
			//折扣金额
			accountPaymentDetail.setAccountDiscountCash(discountCash.negate());
		}
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		//写入数据库主表
		dao.insert(accountPaymentDetail);
		
		return accountPaymentDetail;
	}

	

	//现金折扣核销记录插入
	@Transactional
	@Override
	public AccountPaymentDetail accountPaymentDetailDKHXInsert(
			String writeOffNo,
			
			int cashSettle,
			
			String revOpay,
			int direction,
			
			String clearType,
			String clearTypeLabel,
			
			String billType,
			String billTypeName,
			
			String origin,
			String originName,
			String originNo,
			
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,

			BigDecimal discountCash,
			
			String captionID,
			String captionNo,
			String captionName,
			String captionFullName,
			
			String cUsercode,String cUsername,String userId,
			String employeeNo,String employeeName,
			
			String enterpriseNo,
			String enterpriseName
			){

		
//		String revOpay = "I";
//		
//		String clearType = "6";
//		String clearTypeLabel = "6.到款核销";
//		
//		String billType = "SKHX";
//		String billTypeName = "收款核销";
		
//		int direction = 1;
		
//		Date invoiceDate = Utils.getCurrentDate();
		String invoiceCode = null;
		
		BigDecimal orderAmount = discountCash;
		BigDecimal pendingAmount = discountCash;
		BigDecimal orderAmountCleared = discountCash;
		
		//打包主表AccountPayment
		AccountPaymentDetail accountPayment = this.packing(cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		accountPayment.setCashSettle(cashSettle);
		
		accountPayment.setClearType(clearType);
		accountPayment.setClearTypeLabel(clearTypeLabel);
		accountPayment.setBillType(billType);//款项类别
		accountPayment.setBillTypeName(billTypeName);//款项类别
		
		accountPayment.setState("confirm");
		accountPayment.setAudit("confirm");
//		accountPayment.setResultStatus("已审核");
		accountPayment.setOrderDate(Utils.getCurrentDate());
		accountPayment.setConfirmDate(Utils.getCurrentDate());
	
		accountPayment.setAccountPaymentNo(writeOffNo);
		
		accountPayment.setDirection(direction);
		accountPayment.setRevOpay(revOpay);
		
		accountPayment.setEmployeeNo(employeeNo);
		accountPayment.setEmployeeName(employeeName);
		
		accountPayment.setOrigin(origin);
		accountPayment.setOriginName(originName);
		accountPayment.setOriginNo(originNo);
		
		accountPayment.setDealObject(dealObject);
		accountPayment.setDealObjectLabel(dealObjectLabel);
		accountPayment.setCustomerID(customerID);
		accountPayment.setCustomerNo(customerNo);
		accountPayment.setShortName(shortName);
		accountPayment.setCustomerName(customerName);
		
//		accountPayment.setSettleDate(invoiceDate);
		accountPayment.setSettleCode(invoiceCode);
		
		accountPayment.setCaptionID(captionID);
		accountPayment.setCaptionNo(captionNo);
		accountPayment.setCaptionName(captionName);
		accountPayment.setCaptionFullName(captionFullName);
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		accountPayment.setOrderAmount(orderAmount);//应收票据金额
		accountPayment.setPendingAmount(pendingAmount);//应收票据余额
		accountPayment.setOrderAmountCleared(orderAmountCleared);//核销金额
		accountPayment.setDiscountCash(BigDecimal.ZERO);//折扣金额

		//账
		BigDecimal accountAmountCleared = orderAmountCleared.multiply(new BigDecimal(direction)).setScale(2);
		
		accountPayment.setAccountClearActual(accountAmountCleared);
		accountPayment.setAccountDiscountCash(BigDecimal.ZERO);
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		//写入数据库主表
		dao.insert(accountPayment);
		
		return accountPayment;
	}
	

	//核销记录删除
	@Transactional
	@Override
	public void accountPaymentDetailDKHXDelete(String writeOffNo, String billType, String originNo, String enterpriseNo) {
		AccountPaymentDetail obj = dao.getByNo(writeOffNo, billType, originNo, enterpriseNo);
		if(obj!=null) {
			dao.delete(obj.getfID());
		}
	}



	
	


	
	
}
